package main

import (
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"time"
	"xorm.io/xorm"
)

func main() {

	type User struct {
		Id      int64
		Name    string
		Age     int
		Passwd  string    `xorm:"varchar(200)"`
		Created time.Time `xorm:"created"`
		Updated time.Time `xorm:"updated"`
	}

	// 数据库连接基本信息
	var (
		userName  string = "root"
		password  string = "123456"
		ipAddress string = "127.0.0.12.9"
		port      int    = 3306
		dbName    string = "go_project"
		charset   string = "utf8mb4"
	)
	// 构建数据库连接信息
	dataSourceName := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=%s", userName, password, ipAddress, port, dbName, charset)

	engine, err := xorm.NewEngine("mysql", dataSourceName)
	if err != nil {
		fmt.Println("mysql connect fair!")
	}

	// engine.Sync
	err = engine.Sync(new(User))
	if err != nil {
		fmt.Println("tables sync fair!")
	}

	// 事务

	session := engine.NewSession()
	defer session.Close()

	session.Begin()
	defer func() {
		err := recover()
		if err != nil {
			// 回滚
			fmt.Println(err)
			fmt.Println("rollback")
			session.Rollback()
		} else {
			session.Commit()
		}
	}()

	user1 := User{Id: 10005, Name: "xiaomin", Age: 85, Passwd: "456789123"}
	if _, err := session.Insert(&user1); err != nil {
		panic(err)
	}

	user2 := User{Name: "Jackson", Age: 61}
	if _, err := session.Where("id=1004").Update(&user2); err != nil {
		panic(err)
	}

	if _, err := session.Exec("delete from user where name = 'java'",); err != nil {
		panic(err)
	}


}
